package com.fengye.security.demo.config;

import com.fengye.security.demo.model.Perm;
import com.fengye.security.demo.service.PermService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
// @Component
public class AppFilterInvocationSecurityMetadataSource implements org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource {

    private FilterInvocationSecurityMetadataSource superMetadataSource;

    // @Autowired
    private PermService permService;

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    public AppFilterInvocationSecurityMetadataSource(FilterInvocationSecurityMetadataSource expressionBasedFilterInvocationSecurityMetadataSource){
         this.superMetadataSource = expressionBasedFilterInvocationSecurityMetadataSource;

         // TODO 从数据库加载权限配置
    }
    public AppFilterInvocationSecurityMetadataSource(FilterInvocationSecurityMetadataSource expressionBasedFilterInvocationSecurityMetadataSource, PermService permService){
         this.superMetadataSource = expressionBasedFilterInvocationSecurityMetadataSource;
         this.permService = permService;

         // TODO 从数据库加载权限配置
    }

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    
	// 这里的需要从DB加载
    private final Map<String,String> urlRoleMap = new HashMap<String,String>(){{
        put("/open/**","ROLE_ANONYMOUS");
        put("/health","ROLE_ANONYMOUS");
        put("/restart","ROLE_ADMIN");
        put("/demo","ROLE_USER");
    }};

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();

        log.info("url={}", url);
        String method = fi.getRequest().getMethod();
        log.info("method={}", method);

        try{
            List<Perm> perms = permService.list();
            for (Perm item : perms) {
                if (antPathMatcher.match(item.getUrl(), url)) {
                    String itemMethod = item.getMethod();
                    if (StringUtils.isEmpty(itemMethod) || StringUtils.commaDelimitedListToSet(itemMethod).contains(method) || antPathMatcher.match(itemMethod, method)) {
                        log.info("命中权限: {}", item.getPe());
                        // return SecurityConfig.createList("hasAuthority('"+item.getPe()+"')");
                        return SecurityConfig.createList(item.getPe());
                    }

                }
            }

      // for(Map.Entry<String,String> entry:urlRoleMap.entrySet()){
      //     if(antPathMatcher.match(entry.getKey(),url)){
      //         return SecurityConfig.createList(entry.getValue());
      //     }
      // }
    } catch (Exception e) {
      log.info("perms为空");
      e.printStackTrace();
}
        //  返回代码定义的默认配置
        // return superMetadataSource.getAttributes(object);
        // return  SecurityConfig.createList("");
        return null;
    }



    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}